package com.usefullc.user.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.usefullc.common.enums.YesNoEnum;
import com.usefullc.common.util.BeanUtils;
import com.usefullc.user.domain.Tenant;
import com.usefullc.user.domain.TenantUser;
import com.usefullc.user.domain.User;
import com.usefullc.user.mapper.TenantUserMapper;
import com.usefullc.user.query.TenantQuery;
import com.usefullc.user.query.TenantUserQuery;
import com.usefullc.user.vo.TenantUserVo;
import com.usefullc.system.entity.Pager;
import com.usefullc.system.service.AbstractBizService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 租户用户服务类
 * @author: 星空
 * @date: 2022-10-05
 */
@Service
public class TenantUserService extends AbstractBizService<TenantUserMapper, TenantUser, TenantUserQuery> {


    @Autowired
    private UserService userService;

    @Override
    protected QueryWrapper<TenantUser> getQueryWrapper(TenantUserQuery query) {
        QueryWrapper<TenantUser> queryWrapper = super.getQueryWrapper(query);
        return queryWrapper;
    }

    public Pager<TenantUserVo> findVoByPage(TenantUserQuery query){
        Pager<TenantUser> page = this.findByPage(query);
        Pager<TenantUserVo> newPage = new Pager<>(page);
        List<TenantUser> dataList = page.getDataList();
        List<TenantUserVo> newDataList = new ArrayList<>();
        newPage.setDataList(newDataList);
        for (TenantUser tenantUser : dataList) {
            TenantUserVo tenantUserVo = BeanUtils.beanCopy(tenantUser, TenantUserVo.class);
            newDataList.add(tenantUserVo);
        }
        return newPage;
    }

    public TenantUser findByUserIdAndTenantId(Long userId,Long tenantId){
        TenantUserQuery query = new TenantUserQuery();
        query.setUserId(userId);
        query.setTenantId(tenantId);
        return this.findOne(query);

    }


    /**
     * 切换租户，无需重新登录，如果切换后，状态未审核需要审核通过后，才能操作
     * @param userId
     * @param tenantId
     * @return
     */
    public int switchTenant(Long userId,Long tenantId){
        TenantUser tenantUser = this.findByUserIdAndTenantId(userId, tenantId);
        if(tenantUser == null){
            tenantUser = new TenantUser();
            tenantUser.setUserId(userId);
            tenantUser.setTenantId(tenantId);
            tenantUser.setStatus(YesNoEnum.NO.getCode());
        }
//        tenantUser.setGmtAudit(new Date());
//        tenantUser.setAuditUserId(loginUser.getUserId());
        this.save(tenantUser);

        //
        User user = userService.findById(userId);
        user.setTenantId(tenantUser.getId());
        userService.update(user);//修改用户租户ID
        return 1;

    }


}
